package script.mainpage
{
	import eventUtil.EventCenter;
	
	import laya.components.Script;
	import laya.display.Input;
	import laya.events.Event;
	import laya.utils.Handler;
	
	import model.HttpErrorCode;
	import model.HttpRequestUtil;
	import model.Userdata;
	import model.goods.UserCartGoodsVo;
	
	import script.ViewManager;
	import script.mainpage.items.UserCartGoodsCell;
	
	import ui.tabview.UserCartPanelUI;
	
	import utils.UtilTool;
	
	public class UserCartController extends Script
	{
		private var uiSkin:UserCartPanelUI
		public function UserCartController()
		{
			super();
		}
		
		override public function onStart():void
		{
			uiSkin = this.owner as UserCartPanelUI;
			
			uiSkin.userCartList.itemRender = UserCartGoodsCell;
			
			uiSkin.userCartList.vScrollBarSkin = "";
			uiSkin.userCartList.spaceY = 5;
			uiSkin.userCartList.renderHandler = new Handler(this, updateGoodsList);
			//uiSkin.userCartList.selectHandler = new Handler(this,selectGoods);
			//uiSkin.userCartList.selectEnable = true;
			uiSkin.userCartList.array = [];
			
			uiSkin.address.text = Userdata.instance.address != ""?Userdata.instance.address:"未设置您的收货地址，请点击修改按钮设置您的收货地址";
			uiSkin.changeAddress.visible = false;
			
			uiSkin.changgeAddressInput.maxChars = 50;
			
			uiSkin.emptytip.visible = false;
			
			uiSkin.updateAddress.on(Event.CLICK,this,function(e:Event){
				
				uiSkin.changeAddress.visible = true;
				uiSkin.address.visible = false;
				uiSkin.changgeAddressInput.text = Userdata.instance.address;
				e.stopPropagation();
				
			})
				
			uiSkin.confirmAddress.on(Event.CLICK,this,function(){
				
				uiSkin.changeAddress.visible = false;
				uiSkin.address.visible = true;
				
				if(uiSkin.changgeAddressInput.text.length > 6)
				{
					var postdata:String = "address=" + uiSkin.changgeAddressInput.text
					HttpRequestUtil.instance.Request(HttpRequestUtil.httpUrl + HttpRequestUtil.setUserAddress,this,updateAddress,postdata,"post");
				
				}
				else
				{
					ViewManager.showAlert("地址太短");
				}

				
			})
				
			uiSkin.on(Event.CLICK,this,function(e:Event){
				
				if(e.target is Input)
					return;
				
				uiSkin.changeAddress.visible = false;
			});
			
			
			uiSkin.confirmOrder.on(Event.CLICK,this,showConfirmPanel);
			
			
			uiSkin.userInfo.text = Userdata.instance.userName + "  " + Userdata.instance.userAccount;
			uiSkin.selectall.selected = false;
			uiSkin.selectall.label = "已选0";
			uiSkin.selectall.on(Event.CLICK,this,onSelectedAll);
			
			EventCenter.instance.on(EventCenter.SELECTE_USERCART_GOODS,this,selectGoods);
			EventCenter.instance.on(EventCenter.UPDATE_USERCART_GOODS_COUNT,this,updateGoodsCount);

			HttpRequestUtil.instance.Request(HttpRequestUtil.httpUrl + HttpRequestUtil.getUserCartList,this,onGetGoodsBack,null,"post");
			
		}
		
		
		private function updateGoodsList(cell:UserCartGoodsCell):void
		{
			cell.setData(cell.dataSource);
		}
		private function onGetGoodsBack(data:Object):void
		{
			if(uiSkin.destroyed)
				return;
			var result:Object = JSON.parse(data as String);
			
			if(result.code == HttpErrorCode.OK)
			{
				var goodslist:Array = [];
				var defaultSelectGoods:String = UtilTool.getLocalVar("selectGoods","");
				var curdate:String = UtilTool.formatFullDateTime(new Date(),false);
				
				var hasSelectGoodsList:Array = [];
				if(defaultSelectGoods != "")
				{
					var selectGoods:Object = JSON.parse(defaultSelectGoods);
					if(selectGoods.date == curdate)
						hasSelectGoodsList = selectGoods.selectGoods;
				}

				for(var i:int=0;i < result.data.length;i++)
				{
					goodslist.push(new UserCartGoodsVo(result.data[i]));
					goodslist[i].selected = hasSelectGoodsList.indexOf(goodslist[i].id) >= 0;
					
				}
				
				uiSkin.userCartList.array = goodslist;
				updateSelectedGoods();
				uiSkin.emptytip.visible = goodslist.length == 0;

			}
			
		}	
		
		private function updateAddress(data:Object):void
		{
			
			if(uiSkin.destroyed)
				return;
			var result:Object = JSON.parse(data as String);
			
			if(result.code == HttpErrorCode.OK)
			{
				Userdata.instance.address = uiSkin.changgeAddressInput.text;
				uiSkin.address.text = Userdata.instance.address;
			}
		}
		
		private function updateGoodsCount(cartid:int,count:int):void
		{
			var arr:Array = uiSkin.userCartList.array;

			for(var i:int=0;i < arr.length;i++)
			{
				if(arr[i].id == cartid)
				{
					if(count > 0)
					{
						arr[i].goodsCount = count;
						break;
					}
					else
					{
						arr.splice(i,1);
						EventCenter.instance.event(EventCenter.UPDATE_USER_CART_NUM);

						break;
					}
				}
			}
			uiSkin.userCartList.refresh();
			updateSelectedGoods();
		}
		private function selectGoods(cartid:int):void
		{
			var defaultSelectGoods:String = UtilTool.getLocalVar("selectGoods","");
			var curdate:String = UtilTool.formatFullDateTime(new Date(),false);
			
			var hasSelectGoodsList:Array = [];
			if(defaultSelectGoods != "")
			{
				var selectGoods:Object = JSON.parse(defaultSelectGoods);
				if(selectGoods.date == curdate)
					hasSelectGoodsList = selectGoods.selectGoods;
			}
			
			if(hasSelectGoodsList.indexOf(cartid) >=0 )
			{
				hasSelectGoodsList.splice(hasSelectGoodsList.indexOf(cartid),1);
			}
			else
				hasSelectGoodsList.push(cartid);
			
			var arr:Array = uiSkin.userCartList.array;
			for(var i:int=0;i < arr.length;i++)
			{
				if(arr[i].id == cartid)
				{
					arr[i].selected = hasSelectGoodsList.indexOf(cartid) >= 0;
					break;
				}
			}
			
			var selectedObj:Object = {"date":curdate,"selectGoods":hasSelectGoodsList};
			UtilTool.setLocalVar("selectGoods",JSON.stringify(selectedObj));
			
			updateSelectedGoods();
		}
		
		private function updateSelectedGoods():void
		{
			var arr:Array = uiSkin.userCartList.array;
			var selectCount:int = 0;
			var totalMoney:Number = 0;
			for(var i:int=0;i < arr.length;i++)
			{
				
				if(arr[i].selected)
				{
					selectCount++;
					totalMoney += arr[i].goods.sellPrice * arr[i].goodsCount;
				}
			}
			
			uiSkin.totalPrice.text = "¥" + totalMoney.toFixed(2);
			uiSkin.selectall.selected = selectCount == arr.length;
			uiSkin.selectall.label = "已选" + selectCount;
			
		}
		
		private function onSelectedAll():void
		{
			var arr:Array = uiSkin.userCartList.array;
			var selectIds:Array = [];
			for(var i:int=0;i < arr.length;i++)
			{
				
				arr[i].selected = uiSkin.selectall.selected;
				if(uiSkin.selectall.selected)
					selectIds.push(arr[i].id);
			}
			
			uiSkin.userCartList.array = arr;
			
			var curdate:String = UtilTool.formatFullDateTime(new Date(),false);
	
			var selectedObj:Object = {"date":curdate,"selectGoods":selectIds};
			UtilTool.setLocalVar("selectGoods",JSON.stringify(selectedObj));
			updateSelectedGoods();
		}
		
		private function showConfirmPanel():void
		{
			var arr:Array = uiSkin.userCartList.array;
			var allgoods:Array = [];
			for(var i:int=0;i < arr.length;i++)
			{
				
				if(arr[i].selected)
				{
					allgoods.push({cartId:arr[i].id,goodsCount:arr[i].goodsCount,goodsPrice:arr[i].goods.sellPrice});
				}
			}
			if(allgoods.length == 0)
			{
				ViewManager.showAlert("请选择商品");
				return;
			}
			var headers:Array = ["Content-Type", "application/json;charset=UTF-8"];

			var psotdata:String = JSON.stringify(allgoods);//"userCartOrderVoList=" + ;
			HttpRequestUtil.instance.Request(HttpRequestUtil.httpUrl + HttpRequestUtil.confirmOrder,this,confirmOrderBack,psotdata,"post",null,true,headers);

			
		}
		
		private function confirmOrderBack(data:Object):void
		{
			if(uiSkin.destroyed)
				return;
			var result:Object = JSON.parse(data as String);
			
			if(result.code == HttpErrorCode.OK)
			{
				ViewManager.instance.openView(ViewManager.VIEW_CONFIRM_PAY_PANEL,false,result.data);
				HttpRequestUtil.instance.Request(HttpRequestUtil.httpUrl + HttpRequestUtil.getUserCartList,this,onGetGoodsBack,null,"post");
				EventCenter.instance.event(EventCenter.UPDATE_USER_CART_NUM);

			}
		}
		public override function onDestroy():void
		{
			EventCenter.instance.off(EventCenter.SELECTE_USERCART_GOODS,this,selectGoods);
			EventCenter.instance.off(EventCenter.UPDATE_USERCART_GOODS_COUNT,this,updateGoodsCount);

		}
	}
}